package com.tool.cn.mybaties.optimal;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import org.mybatis.generator.api.ShellRunner;

import com.tool.cn.mybaties.optimal.core.CreateXmlContent;
import com.tool.cn.mybaties.optimal.core.ObjectModel;

/**
 * 
 * @author wangzonghui
 * @date 2022年5月10日 上午9:55:53 
 * @Description 加强mybaties模型类输出
 */
public class CreateModelXml {

	public static void main(String[] args) {
		
		String project="D:\\workspace202003\\think-object";
		//生成xml缓存文件
		ObjectModel objectModel = new ObjectModel("test",project);
		objectModel.modelPath="com.think.cn.mybaties.model";
		objectModel.mapperPath="com.think.cn.mybaties.mapper";
		objectModel.xmlPath="src.main.java.com.think.cn.mybaties";
		
		//表和模型类对应关系，可以多个
		objectModel.tableRelation.put("test", "TestModel");
		
		//生成xml、实体类、mapper类
		createModelXml(objectModel);
	}
	
	@SuppressWarnings("static-access")
	public static void createModelXml(ObjectModel objectModel) {
		//生成xml配置文件
		String result=new CreateXmlContent().createContent(objectModel);
		String path=tmpFile(result);
		
		//生成模型类+xml
		new ShellRunner().main(new String[]{"-configfile",path,"-overwrite"});
	}
	
	/**
	 * 生成临时文件，程序结束后删除
	 * @return 文件绝对路径
	 */
    public static String tmpFile(String content) {
         File xmlFile = null;
         PrintWriter writer = null;
        try {
            xmlFile  = File.createTempFile("generator",".xml");
            writer = new PrintWriter(xmlFile);
            writer.println(content);
            
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            
             if (writer != null) {
                  writer.close();
             }
             xmlFile.deleteOnExit();
        }
        return xmlFile.getAbsolutePath();
    }
}
